import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import UserService from '@/api/UserService'

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  if (whiteList.indexOf(to.path) !== -1) {
    // 在免登录白名单，直接进入
    next()
  } else if (UserService.tokenExists()) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({path: '/'})
      NProgress.done()
    } else {
      const authorityList = store.getters.authorityList
      if (authorityList.length > 0) {
        // 当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
        next()
      } else {
        try {
          // 刷新页面之后登录信息丢失，重新获取登录用户信息
          const user = await store.dispatch('user/current')
          // 生成可访问的路由表
          const accessRoutes = await store.dispatch('permission/generateRoutes', user.authorityList)
          // 动态挂载路由
          router.addRoutes(accessRoutes)
          // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          next({...to, replace: true})
          // next({...to})
          // next()
        } catch (error) {
          console.error(error)
          // remove token and go to login page to re-login
          await store.dispatch('user/clearToken')
          // Message.error(error || 'Has Error')
          next(`/login${to.path === '/dashboard' ? '' : `?redirect=${to.path}`}`)
          NProgress.done()
        }
      }
    }
  } else {
    // other pages that do not have permission to access are redirected to the login page.
    next(`/login${to.path === '/dashboard' ? '' : `?redirect=${to.path}`}`)
    NProgress.done()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
